<template>
  <div id="app">
    <el-dialog
        :close-on-click-modal="false"
        :visible.sync="addReimburseDialog"
        :title="title"
        width="40%"
        top="50px"
        center
        @closed="loading = false"
    >
      <div class="flexBox">
        <p><span>*</span>报销一级分类:</p>
        <el-select
            clearable
            size="small"
            :disabled="disabled"
            style="width: 350px"
            placeholder="请选择一级分类"
            v-model="parpmsData.financeId"
            @change="changeFinanceId"
        >
          <el-option
              v-for="(e, i) in oneType"
              :label="e.financeName"
              :key="i"
              :value="e.financeId"
          ></el-option>
        </el-select>
      </div>
      <div class="flexBox" v-if="twoType.length">
        <p><span>*</span>报销二级分类:</p>
        <el-select
            clearable
            size="small"
            style="width: 350px"
            placeholder="请选择二级分类"
            v-model="parpmsData.financeLevelId"
        >
          <el-option
              v-for="(e, i) in twoType"
              :label="e.levelName"
              :key="i"
              :value="e.id"
          ></el-option>
        </el-select>
      </div>

      <template v-if="parpmsData.financeId && parpmsData.financeLevelId">
        <div class="flexBox" v-if="[13,14,15].includes(parpmsData.financeId)">
          <p>订单名称:</p>
          <el-input size="small" style="width:350px" placeholder="请输入订单名称" v-model="parpmsData.storeName"></el-input>
        </div>
        <div
            class="flexBox"
            v-if="![1,2,13,14,15,16].includes(parpmsData.financeId)"
        >
          <p>店铺名称：</p>
          <!-- <span>*</span> -->
          <el-select
              filterable
              remote
              :disabled="disabled"
              :remote-method="remoteMethod"
              value-key="orderId"
              clearable
              v-model="parpmsData.orderId"
              size="small"
              @input="chooseStoreName"
              style="width: 350px"
              placeholder="请输入店铺名称"
          >
            <el-option
                v-for="item in saleNameList"
                :key="item.orderId"
                :label="item.storeName"
                :value="item.orderId"
            >
            </el-option>
          </el-select>
          <div style="margin-left: 2px" v-if="selectedData">去货架日期：{{ selectedData }}</div>
        </div>
        <div
            class="flexBox"
            v-if="
            parpmsData.financeId != 2 &&
            ([1,3,4,13,14,15,16].includes(parpmsData.financeId))
          "
        >
          <p>所属区域：</p>
          <!-- <span>*</span> -->
          <el-select
              size="small"
              style="width: 350px"
              placeholder="请选择所属区域"
              v-model="parpmsData.areaId"
          >
            <el-option
                :label="item.areaName"
                :value="item.area"
                :key="item.area"
                v-for="item in areaData"
            ></el-option>
          </el-select>
        </div>
        <div
            class="flexBox"
            v-if="parpmsData.financeId != 1 && parpmsData.financeId != 2"
        >
          <p>责任主体：</p>
          <!-- <span>*</span> -->
          <el-select
              size="small"
              style="width: 350px"
              placeholder="请选择责任主体"
              v-model="parpmsData.optioner"
              @change="changeResponsibility"
          >
            <el-option
                :label="item.optionerName"
                :value="item.id"
                :key="item.id"
                v-for="item in responsibility"
            ></el-option>
          </el-select>
        </div>
        <div
            class="flexBox"
            v-if="
            parpmsData.financeId != 1 &&
            parpmsData.financeId != 2 &&
            reimburseTypeData.length
          "
        >
          <p>报销原因类型：</p>
          <!-- <span>*</span> -->
          <el-select
              size="small"
              style="width: 350px"
              placeholder="请选择报销原因类型"
              v-model="parpmsData.reimburseType"
          >
            <el-option
                :label="item.reimburseType"
                :value="item.id"
                :key="item.id"
                v-for="item in reimburseTypeData"
            ></el-option>
          </el-select>
        </div>

        <div class="flexBox" v-if="parpmsData.financeLevelId === 20">
          <p>零时工人数：</p>
          <!-- <span>*</span> -->
          <el-input
              v-model="parpmsData.temporaryWorkerNum"
              size="small"
              style="width: 350px"
          ></el-input>
        </div>
        <div class="flexBox">
          <p>报销原因说明：</p>
          <el-input
              v-model="parpmsData.reimburseRemark"
              type="textarea"
              size="small"
              style="width: 350px"
          ></el-input>
        </div>
        <div class="flexBox">
          <p><span>*</span>报销金额：</p>
          <el-input
              v-model="parpmsData.money"
              type="number"
              style="width: 350px"
              size="small"
          ></el-input>
        </div>
        <!-- 内部人员 -->
        <!--          <el-select-->
        <!--              filterable-->
        <!--              remote-->
        <!--              v-if="jsrType === 1"-->
        <!--              :remote-method="remoteMethodReimburseRecipient"-->
        <!--              value-key="userName"-->
        <!--              clearable-->
        <!--              v-model="parpmsData.reimburseRecipient"-->
        <!--              size="small"-->
        <!--              style="width: 350px"-->
        <!--              placeholder="请输入并选择报销接收人"-->
        <!--          >-->
        <!--            <el-option-->
        <!--                :label="item.username"-->
        <!--                :value="item.username"-->
        <!--                :key="item.id"-->
        <!--                v-for="item in receiveData"-->
        <!--            ></el-option>-->
        <!--          </el-select>-->

        <!-- 外部人员 -->

        <div class="flexBox">
          <p>收款方式：</p>
          <el-radio-group
              @input="paymentMethodChange"
              v-model="parpmsData.paymentMethod"
              v-removeAriaHidden
          >
            <el-radio :label="1">银行卡</el-radio>
            <el-radio :label="2">微信</el-radio>
            <el-radio :label="3">支付宝</el-radio>
          </el-radio-group>
        </div>
        <div
            style="
            border: 1px solid #82848a;
            width: 420px;
            padding-top: 20px;
            padding-right: 40px;
            padding-bottom: 10px;
            margin-bottom: 15px;
            margin-left: 30px;
          "
            v-if="parpmsData.paymentMethod == 1"
        >
          <div class="flexBox">
            <p>户名：</p>
            <el-input v-model="parpmsData.cardName" size="small"></el-input>
          </div>
          <div class="flexBox">
            <p>卡号：</p>
            <el-input v-model="parpmsData.cardNo" size="small"></el-input>
          </div>
          <div class="flexBox">
            <p>开户行：</p>
            <el-input v-model="parpmsData.bankName" size="small"></el-input>
          </div>
        </div>
        <div
            v-if="parpmsData.paymentMethod == 2 || parpmsData.paymentMethod == 3"
            style="display: flex; margin-bottom: 15px; margin-left: 150px"
        >
          <div style="display: flex">
            <el-upload
                class="upload-demo"
                :multiple="false"
                drag
                :show-file-list="title === '编辑' ? false : true"
                :on-change="handleChangePic"
                list-type="picture"
                :headers="headerToken"
                :on-success="onSuccess"
                :action="`${$apiHost}/common/fileImgUrl`"
            >
              <i class="el-icon-upload" style="color: #66b1ff"></i>
              <div class="el-upload__text" style="color: #66b1ff">
                <em>点击或拖拽微信/支付宝二维码图片</em>
              </div>
            </el-upload>
          </div>
          <el-image
              style="width: 50px; height: 50px"
              v-if="title === '编辑' && payUrl"
              ref="preview"
              :src="host + payUrl"
              :preview-src-list="[host + payUrl]"
          >
          </el-image>
        </div>
        <div class="flexBox">
          <p>报销凭证：</p>
          <uploaderMore
              v-model="payImgArray"
              :isDrag="true"
              :limit="30"
          ></uploaderMore>
          <div v-if="qrCode" class="qrCode" style="display: flex;flex-direction: column;align-items: center">
            <el-image :src="qrCode" style="width: 150px;"></el-image>
            <el-button size="small" type="primary" style="margin-top: 10px" @click="recipePhonePic">接收手机端图片
            </el-button>
          </div>
        </div>
        <div class="flexBox">
          <p>报销文件：</p>
          <el-upload
              class="upload-demo"
              accept=".xls,.XLS,.xlsx,.XLSX"
              :show-file-list="true"
              :headers="headers"
              :action="`${$apiHost}/common/excelImg`"
              :on-success="onSuccessExcel"
              :before-upload="beforeUpload"
              :on-error="onError"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div class="el-upload__tip" slot="tip">只能上传excel文件</div>
          </el-upload>
          <!-- <el-link>{{ parpmsData.reimburseExcelUrl }}</el-link> -->
        </div>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addReimburseDialog = false">取 消</el-button>
        <el-button
            v-if="!disabled"
            type="primary"
            @click="addInfoNew(1)"
            v-preventReClick
        >确 定</el-button
        >
        <!-- :loading="loading" -->
        <el-button
            type="primary"
            @click="addInfoNew(2)"
            :loading="loading"
            v-if="disabled"
        >修 改</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import store from '../../../store'
import UploaderMore from '../../../components/Element/UploaderMore.vue'
import uploadExcel from '../components/uploadExcel.vue'
import quinn from "../../../utils/quinn";

export default {
  name: 'addReimburseNew',
  components: {
    UploaderMore,
    uploadExcel,
  },
  data() {
    return {
      uploadLoading: null,
      jsrType: 1,
      qrCode: "",
      payImgArray: [],
      receiveData: [], //报销接收人
      responsibility: [], //责任主体
      reimburseTypeData: [], //报销原因类型
      areaData: [],
      ppTypeList: [],
      parpmsData: {
        financeId: null, //一级
        financeLevelId: null, //二级
        orderId: null,
        // systemType: null,
        areaId: null, //区域
        optioner: null, //责任主体
        reimburseType: null, //报销原因类型
        temporaryWorkerNum: 0, //临时工人数
        reimburseRemark: '', //报销原因说明
        money: 0, //报销金额
        reimburseRecipient: '', //报销接收人
        paymentMethod: null, //收款方式
        cardName: '', //户名/持卡人名称
        cardNo: '', //银行卡号
        bankName: '', //开户行/银行名称
        payUrl: '', //收款二维码
        proof: [], //报销凭证
        reimburseExcelUrl: '',
        storeName: "",
      },

      preSalesImg: [],
      addReimburseDialog: false,
      storeName: '',
      host: this.$imgHost,
      typeText: '',
      disabled: false,
      paymentMethod: '',
      saleNameList: [],
      fileList: [],
      preSalesImgList: [],
      productImgs: [],
      bankName: '',
      title: '',
      editId: '',
      orderIdReal: '',
      financeId: '',
      levelId: '',
      matter: '',
      remark: '',
      cardNo: '',
      cardName: '',
      paymentType: '',
      orderId: '',
      money: '',
      optioner: '',
      proof: [],
      SaleTypeData: [],
      payUrl: [],
      options: [],
      addStatus: '',
      type: [],
      loading: false,

      oneType: [],
      twoType: [],
      selectedData: "",
    }
  },
  computed: {
    headerToken() {
      const token = store.state.token
      return {
        token,
      }
    },
    headers() {
      const token = store.state.token
      return {
        token,
      }
    },
  },
  created() {
    const {userName = [], id = []} = quinn.getStorage('userData') || {}
    this.userName = userName
    this.userId = id
    this.uploadLoading = null
    document.addEventListener('paste', this.handlePaste)
    this.getTypeList()

    this.$api.financeOneType().then((res) => {
      this.oneType = []
      this.twoType = []
      this.oneType = res
    })
    this.$api.orderGetSystemTypeVo().then((res) => {
      this.ppTypeList = []
      this.ppTypeList = res
    })
    this.$api.areaLedgerAreaList().then((res) => {
      this.areaData = []
      this.areaData = res
    })
    this.$api.financeGetOptionerType().then((res) => {
      this.responsibility = []
      this.responsibility = res
    })
  },
  methods: {
    recipePhonePic() {
      this.$api.accountGetUserUploadImgUrl().then(res => {
        if (res) {
          console.log(res.split(','))
          this.payImgArray.push(...res.split(','))
        } else {
          this.$message.warning('暂无图片！')
        }
      })
    },
    checkClosed(val){
      console.log(val,'11')
    },
    chooseStoreName(val) {
      const selected = this.saleNameList.find(item => item.orderId === val)
      this.selectedData = selected.deliveryDate
      // this.$api.orderValidateDeliveryDateFinance({orderId:val})
    },
    removeStatus1() {
      this.parpmsData.reimburseExcelUrl = ''
    },
    onError() {
      this.$message('导入失败')
    },
    beforeUpload(res) {
      console.log('开始上传', res)
      this.uploadLoading = this.$loading({
        lock: true,
        text: '上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
    },
    onSuccessExcel(res) {
      if (res.code != 200) {
        this.$message(res.msg)
        this.uploadLoading.close()
        //  setTimeout(() => {
        //   loading.close();
        // }, 2000);
      } else {
        this.$message({message: '导入成功！', type: 'success'})
        console.log(res)
        // if (res.result[0]) {
        //   this.parpmsData.reimburseExcelUrl = res.result[0]
        // }
        if (res.result) {
          this.parpmsData.reimburseExcelUrl = res.result
        }
        this.uploadLoading.close()
      }
    },
    changeResponsibility(e) {
      console.log('责任主体变化', e)
      if (e) {
        this.parpmsData.reimburseType = null
        this.$api
            .financeGetReimburseTypeByOid({optionerId: e})
            .then((res) => {
              console.log('联动出的原因类型', res)
              this.reimburseTypeData = []
              this.reimburseTypeData = res
            })
      }
    },
    jsrTypeChange(e) {
      if (e) {
        this.parpmsData.reimburseRecipient = ''
      }
    },
    changeFinanceId(e) {
      this.parpmsData.financeLevelId = null
      this.twoType = []
      if (e) {
        if (e == 1 || e == 2) {
          this.parpmsData.optioner = 5
          this.parpmsData.reimburseType = 15
        }
        this.$api
            .financeGetFinanceLevelTypeByFid({financeId: e})
            .then((res) => {
              console.log('联动出的二级', res)

              this.twoType = res
            })
      }
    },
    deletePic(i) {
      this.proof.splice(i, 1)
    },
    getTypeList() {
      this.$api.newAfterSaleTypesEnum().then((res) => {
        this.SaleTypeData = res
      })
    },
    handlePaste(event) {
      if (!this.addReimburseDialog) return
      const clipboardData = event.clipboardData || window.clipboardData
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i]
          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile()
            if (file) {
              this.uploadImage(file)
            }
          } else if (item.kind === 'string' && item.type.startsWith('text/')) {
            console.log('text')
          } else {
            this.$message.error('请拷贝图片!')
            break
          }
        }
      }
    },
    uploadImage(imageFile) {
      const formData = new FormData()
      formData.append('file', imageFile)
      for (let [key, value] of formData.entries()) {
        console.log(`${key}:`, value)
      }
      if (imageFile.size > 5000000)
        return this.$message.warning('图片大于5MB，请压缩后上传！')
      axios
          .post(`${this.$apiHost}/common/fileImgUrl`, formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: store.state.token,
            },
          })
          .then((response) => {
            this.payImgArray.push(response.data.result[0])
          })
          .catch((error) => {
          })
    },
    handleChangePic(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
        this.payUrl = fileList
      }
    },
    async handleOpen(data) {
      this.$api.wxUserUploadImg({userId: this.userId}).then(res => {
        this.qrCode = 'data:image/png;base64,' + res
      })
      if (data) {
        console.log('编辑')
        this.title = '编辑'
        this.editId = data.id
        this.disabled = true
        await this.changeFinanceId(data.financeId)
        await this.remoteMethod(data.storeName)
        await this.changeResponsibility(data.optionerId)
        if (data) {
          for (let key in data) {
            if (this.parpmsData.hasOwnProperty(key)) {
              this.parpmsData[key] = data[key]
              this.payUrl = data.payUrl
              this.payImgArray = data.proofStr.split(',')
              // this.parpmsData.orderId = data.orderId
              this.parpmsData.optioner = data.optionerId
              this.parpmsData.reimburseType = data.reimburseTypeId
              // this.parpmsData.storeManagerId = data.storeManagerId
            }
          }
        }
      } else {
        console.log('新增')
        this.disabled = false
        this.title = '新增'
        this.payImgArray = []
        this.parpmsData = this.$options.data.call(this).parpmsData
      }
      this.addReimburseDialog = true
      this.getType()
    },
    async getType() {
      const res = await this.$api.storeLedgerGetFinanceLevelTypeDto()
      this.type = res
    },
    // remoteMethodReimburseRecipient(val) {
    //   if (val) {
    //     const params = {
    //       userName: val,
    //     }
    //     this.$api.userGetUserNameByUserName(params).then((res) => {
    //       this.receiveData = []
    //       this.receiveData = res
    //     })
    //   }
    // },
    remoteMethod(val) {
      if (val) {
        const params = {
          storeName: val,
        }
        this.$api.orderGetOrderInfoLikeName(params).then((res) => {
          this.saleNameList = res
        })
      }
    },
    onSuccess(res) {
      const {productImgs = []} = this
      if (res.code == 200 && res.result) {
        this.payUrl = res.result[0]
        // this.disabled = false
      }
    },
    paymentMethodChange(e) {
      console.log('付款方式改变', e)
      if (e === 1) {
        this.parpmsData.cardName = ''
        this.parpmsData.cardNo = ''
        this.parpmsData.bankName = ''
      } else {
        this.payUrl = ''
        this.parpmsData.payUrl = ''
      }
    },
    addInfoNew(val) {
      if (!this.parpmsData.financeId || !this.parpmsData.financeLevelId) {
        return this.$message.warning('请选择一二级分类!')
      }
      if (
          ![1, 2, 13, 14, 15].includes(this.parpmsData.financeId)
      ) {
        if (!this.parpmsData.orderId) {
          return this.$message.warning('请输入店铺!')
        }
        if (!this.parpmsData.optioner) {
          return this.$message.warning('请选择责任主体!')
        }
        if (!this.parpmsData.reimburseType) {
          return this.$message.warning('请选择原因类型!')
        }
        if (
            this.parpmsData.financeId == 4 &&
            this.parpmsData.financeLevelId === 20 &&
            !this.parpmsData.temporaryWorkerNum
        ) {
          return this.$message.warning('请输入临时工人数!')
        }
      }
      if (this.parpmsData.financeId === 1) {
        if (!this.parpmsData.areaId) {
          return this.$message.warning('请选择区域!')
        }
      }
      if (!this.parpmsData.money) {
        return this.$message.warning('请输入报销金额!')
      }
      if (!this.parpmsData.paymentMethod) {
        return this.$message.warning('请选择付款方式!')
      }
      if (this.parpmsData.paymentMethod == 1) {
        if (
            !this.parpmsData.cardName ||
            !this.parpmsData.cardNo ||
            !this.parpmsData.bankName
        ) {
          return this.$message.warning('请输入卡相关信息!')
        }
      } else {
        if (!this.payUrl) {
          return this.$message.warning('请上传付款码!')
        } else {
          this.parpmsData.payUrl = this.payUrl
        }
      }
      if (!this.payImgArray.length) {
        return this.$message.warning('请上传报销凭证!')
      } else {
        this.parpmsData.proof = this.payImgArray
      }
      this.loading = true
      this.parpmsData.money = JSON.parse(JSON.stringify(this.parpmsData.money))
      if (val == 1) {
        this.add({...this.parpmsData, type: 0})
      } else if (val == 2) {
        this.edit({...this.parpmsData, id: this.editId, type: 0})
      }
    },
    add(b) {
      this.$api.financeAddFinanceDataReimburse(b).then((res) => {
        console.log('新增', res)
        if (res == 1) {
          this.$message.success('新增成功!')
          this.$emit('addStatus', 1)
          this.addReimburseDialog = false
        }
        this.loading = false
      })
    },
    edit(b) {
      this.$api.financeUpdateFinanceDataInfo(b).then((res) => {
        console.log('编辑', res)
        if (res == 1) {
          this.$message.success('编辑成功!')
          this.$emit('addStatus', 1)
          this.addReimburseDialog = false
        }
        this.loading = false
      })
    },
    addInfo(val) {
      if (this.loading) return
      if (this.paymentMethod == 1) {
        this.payUrl = ''
      } else if (this.paymentMethod == 2 || this.payType == 3) {
        this.cardNo = ''
        this.cardName = ''
        this.bankName = ''
      }
      if (!this.orderId) {
        return this.$message.warning('请输入店铺名称!')
      }
      if (!this.money) {
        return this.$message.warning('请输入报销金额!')
      }
      if (!this.financeId) {
        return this.$message.warning('请选择报销分类!')
      }
      if (!this.optioner) {
        return this.$message.warning('请选择承担主体!')
      }

      // if (!this.paymentMethod) {
      //   return this.$message.warning("请选择付款方式!")
      // }
      // if (this.paymentMethod == 1 && (!this.cardNo || !this.cardName || !this.bankName)) {
      //   return this.$message.warning("请完善银行卡信息!")
      // }
      if (!this.proof.length) {
        return this.$message.warning('请上传报销凭证!')
      }
      // if (!this.matter) {
      //   return this.$message.warning("请填入报销费用说明!")
      // }
      // if (this.paymentMethod != 1 && !this.payUrl) {
      //   return this.$message.warning("请上传微信或支付宝付款码!")
      // }
      const data = {
        orderId: this.orderId,
        money: this.money,
        financeId: this.financeId,
        financeLevelId: this.financeLevelId,
        payUrl: this.payUrl.toString() || '',
        proof: this.proof || '',
        cardNo: this.cardNo,
        optioner: this.optioner,
        cardName: this.cardName,
        bankName: this.bankName,
        matter: this.matter,
        remark: this.remark,
        paymentMethod: this.paymentMethod,
      }
      this.loading = true
      setTimeout(() => {
        this.loading = false
      }, 7000)
      if (val == 'add') {
        this.$api.storeLedgerAddStoreLedgerDetails(data).then((res) => {
          if (res == 1) {
            this.$message.success('新增成功!')
            this.$emit('addStatus', 1)
            this.addReimburseDialog = false
          }
        })
      } else if (this.financeId == 1 && val != 'add') {
        data.status = 4
        data.storeLedgerId = this.storeLedgerId
        data.orderId = this.orderIdReal
        this.$api.storeLedgerUpdateStoreLedgerDetails(data).then((res) => {
          if (res == 1) {
            this.$message.success('修改成功!')
            this.$emit('addStatus', 2)
            this.addReimburseDialog = false
          }
        })
      } else {
        data.storeLedgerId = this.storeLedgerId
        data.orderId = this.orderIdReal
        data.status = 0
        this.$api.storeLedgerUpdateStoreLedgerDetails(data).then((res) => {
          if (res == 1) {
            this.$message.success('修改成功!')
            this.$emit('addStatus', 2)
            this.addReimburseDialog = false
          }
        })
      }
    },
    changeType(val) {
      this.$api.storeLedgerGetFinanceLevelTypeDto().then((res) => {
        const result = res.find((item) => item.levelId === val)
        this.financeId = result.financeId
        this.financeLevelId = result.levelId
      })
    },
  },
}
</script>

<style scoped lang="less">
.flexBox {
  display: flex;
  margin-left: 50px;
  margin-bottom: 15px;
  justify-content: flex-start;
  align-items: center;

  p {
    width: 100px;
  }

  span {
    color: #ce0e0f;
  }

  .el-input {
    width: 300px;
  }
}
</style>
